#!/usr/bin/env python

import pygame, sys

from accel import AccelControl

def input(events): 
   for event in events:
	   if event.type == pygame.QUIT: 
		   sys.exit(0)
	   elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
		   sys.exit(0)

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    try:
        sound = pygame.mixer.Sound(name)
    except pygame.error, message:
        print "Cannot load sound:", name
        raise SystemExit, message
    return sound


if __name__=="__main__":
	pygame.init()

	if not pygame.mixer: print 'Warning, sound disabled'

	#window = pygame.display.set_mode((480, 640))
	window = pygame.display.set_mode((480, 640), pygame.FULLSCREEN)
	
	screen = pygame.display.get_surface() 

	ball=pygame.image.load("data/ball.png")
	sound=load_sound("data/boing.ogg")
	
	a=AccelControl()

	origin=a.read()

	ox,oy,oz=origin

	bx=0
	by=0
	
	dx=0
	dy=0

	print "Ball!"
	while True: 
		input(pygame.event.get())

		acx,acy,acz=a.read()

		ax=(ox-acx)/100.0
		ay=(oy-acy)/100.0
		
		# x is inversed
		dx-=ax
		dy+=ay

		dx*=0.9
		dy*=0.9

		bx+=dx
		by+=dy

		if bx<-220:
			sound.play()
			dx*=-0.9
			bx=-220
		if bx>220:
			sound.play()
			dx*=-0.9
			bx=220
		if by<-300:
			sound.play()
			dy*=0.9
			by=-300
		if by>300:
			sound.play()
			dy*=0.9
			by=300
			
		screen.fill((0,0,0))
		screen.blit(ball, (240+bx-16,320+by-16))	
		pygame.display.flip()

		sys.stdout.write("\r% 5.2f % 5.2f - % 5.2f % 5.2f"%(dx,dy,ax,ay))
		sys.stdout.flush()

